package com.binyouwei.udp_lib.factory;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;

import com.binyouwei.udp_lib.ReceiveMessageInterface;
import com.binyouwei.udp_lib.SingleThreads;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * @author 宾有为
 * @date 2024/6/11 20:05
 * @link https://blog.csdn.net/baidu_41616022?type=blog
 * @describe：
 **/
public class MulticastFactory implements UdpFactory {
    final int port = 6666;
    final String TAG = getClass().getSimpleName();
    boolean isFinish = false;

    @Override
    public void initUdp() {
        isFinish = true;
    }

    @Override
    public void destroyUdp() {
        isFinish = false;
    }

    @Override
    public void sendMessage(@NonNull String ip, @NonNull String message) {
        SingleThreads.getInstance().execute(() -> {
            try {
                // 组播地址，范围在224.0.0.0至239.255.255.255
                InetAddress group = InetAddress.getByName(ip);
                // 将消息转换为字节数组
                byte[] buffer = message.getBytes();
                // 创建DatagramPacket，使用组播地址和端口
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length, group, port);
                // 发送组播消息
                MulticastSocket socket = new MulticastSocket();
                socket.send(packet);
                socket.close();
                Log.e(TAG, "发送广播成功，message：" + message);
            } catch (IOException e) {
                Log.e(TAG, "发送广播失败，message：" + e.getMessage());
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public void onReceiveMessageListener(@NonNull String ip,@NonNull ReceiveMessageInterface receiveMessage) {
        SingleThreads.getInstance().execute(() -> {
            try {
                MulticastSocket socket = new MulticastSocket(port);
                InetAddress group = InetAddress.getByName(ip);
                // 加入组播组，一个设备可加入多个组播组
                socket.joinGroup(group);
                // 创建缓冲区以接收数据
                byte[] receiveData = new byte[1024];
                while (isFinish) {
                    // 创建DatagramPacket来接收数据
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                    // 接收组播消息
                    socket.receive(receivePacket);
                    // 处理接收到的数据
                    String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
                    receiveMessage.onReceiveMessageListener(message);
                    Log.e(TAG, "广播收到一条消息，message：" + message);
                }
                socket.close();
            } catch (IOException e) {
                Log.e(TAG, "广播接收消息失败，message：" + e.getMessage());
                e.printStackTrace();
            }
        });
    }
}
